package com.senseuni.da.utils;

import android.os.CountDownTimer;

import com.elvishew.xlog.XLog;

public abstract class MyCountDownTimer {
    private CountDownTimer countDownTimer;
    private final long mInterval;
    private boolean mIsTimerPaused;
    private long mMillisInFuture;
    private long mRemainingTime;

    public MyCountDownTimer(long millisInFuture, long interval) {
        this.mInterval = interval;
        this.mMillisInFuture = millisInFuture;
        this.mIsTimerPaused = true;
        this.mRemainingTime = millisInFuture;
    }

    public void start() {
        startTimer(mMillisInFuture, mInterval);
    }

    public void start(long millisInFuture) {
        this.mMillisInFuture = millisInFuture;
        this.mRemainingTime = millisInFuture;
        this.mIsTimerPaused = true;
        start();
    }

    public void pause() {
        if (mIsTimerPaused) {
            return;
        }
        stop();
        mIsTimerPaused = true;
    }

    public void resume() {
        if (mIsTimerPaused) {
            startTimer(mRemainingTime, mInterval);
        }
    }

    public void stop() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    private synchronized void startTimer(long millisInFuture, long interval) {
        if (millisInFuture <= 0 || interval <= 0) {
            XLog.e("invalid params.millisInFuture=" + millisInFuture + ", interval=" + interval);
            return;
        }

        if (!mIsTimerPaused) {
            stop();
        }

        if (mIsTimerPaused) {
//            XLog.d("start timer.millisInFuture=" + millisInFuture + ", interval=" + interval);
            countDownTimer = new CountDownTimer(millisInFuture, interval) {
                @Override
                public void onTick(long millisUntilFinished) {
                    mRemainingTime = millisUntilFinished;
                    onTimeTick(millisUntilFinished);
                }

                @Override
                public void onFinish() {
                    onTimeFinish();
                    stop();
                }
            };
            countDownTimer.start();
            mIsTimerPaused = false;
        }

    }

    public abstract void onTimeTick(long value);
    public abstract void onTimeFinish();

}
